<template>
  <el-dialog
    :title="isEdit ? '编辑字典类型' : '新增字典类型'"
    v-model="visible"
    width="500px"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="字典类型编码" prop="code">
        <el-input v-model="form.code" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="字典类型名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { createDictType, updateDictType } from "@/api/dict";

const props = defineProps({
  modelValue: Boolean,
  typeData: Object,
});

const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref();
const loading = ref(false);

const form = reactive({
  id: null,
  code: "",
  name: "",
  description: "",
  status: true,
});

const rules = {
  code: [{ required: true, message: "请输入字典类型编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入字典类型名称", trigger: "blur" }],
};

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const isEdit = computed(() => !!props.typeData);

const resetForm = () => {
  Object.assign(form, {
    id: null,
    code: "",
    name: "",
    description: "",
    status: true,
  });
  formRef.value?.clearValidate();
};

const handleClose = () => {
  visible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (isEdit.value) {
          await updateDictType(form.id, form);
          ElMessage.success("更新成功");
        } else {
          await createDictType(form);
          ElMessage.success("创建成功");
        }
        emit("success");
        handleClose();
      } catch (error) {
        ElMessage.error(error.message || "操作失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

watch(
  () => props.typeData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, {
        id: newVal.id,
        code: newVal.code,
        name: newVal.name,
        description: newVal.description,
        status: newVal.status,
      });
    } else {
      resetForm();
    }
  },
  { immediate: true }
);
</script>